package jk;

public class MyCalendar {
    public static void main(String[] args){
        int year = 2017;
        int month = 11;
        System.out.println(year+"年"+month+"月"+" 的日历：");
        printCalendar(getFirstDay(year,month),getMonthDays(year,month));
    }

    private static void printCalendar(int firstDay , int monthDays){
        int weekCount = 0;
        System.out.print("日\t一\t二\t三\t四\t五\t六\n");
        for(int i=0;i<firstDay;i++){
            System.out.print("\t");
            weekCount++;
        }
        for(int day=1;day<=monthDays;day++){
            System.out.print(day+"\t");
            weekCount++;
            if(weekCount == 7){
                weekCount = 0;
                System.out.println();
            }
        }
    }

    private static int getMonthDays(int year , int month){
        int monthDay = 30;
        switch (month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                monthDay = 31;
                break;
            case 2: {
                if(isYuNian(year)){monthDay = 29;break;}
                else {monthDay = 28;break;}
            }
        }
        return monthDay;
    }

    private static int getFirstDay(int year , int month){
        int daysCount = 0;
        int firstDay;
        for(int i=1970; i<year ; i++){
            daysCount = daysCount+365;
            if(isYuNian(i)){ daysCount++; }
        }
        for(int j=1 ; j<month ; j++){
            daysCount = daysCount+getMonthDays(year,j);
        }
        firstDay = (daysCount%7)+4;
        if(firstDay >= 7){firstDay = firstDay-7;}
        return firstDay;
    }

    private static boolean isYuNian(int year){
        if(year%4 == 0 && year%100 != 0 || year%400 == 0){
            return true;
        }
        else {return false;}
    }
}
